<?php

namespace backend\controllers;

use Yii;
use backend\models\Page;
use backend\models\PageSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use Da\User\Filter\AccessRuleFilter;

/**
 * PageController implements the CRUD actions for Page model.
 */
class PageController extends Controller
{
    

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'ruleConfig' => [
                    'class' => AccessRuleFilter::class,
                ],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'index-list', 'view'],
                        'roles' => ['browsePage'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create'],
                        'roles' => ['createPage'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['update', 'move-up', 'move-down'],
                        'roles' => ['updatePage'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['delete'],
                        'roles' => ['deletePage'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Page models.
     * @return mixed
     */
    public function actionIndex()
    {
        $pagesTreeProvider = Page::findOne(['id' => Yii::$app->config->get('site.vksp')])->populateTree();
        $tvTreeProvider = Page::findOne(['id' => Yii::$app->config->get('site.tv')])->populateTree();
        $zolotoTreeProvider = Page::findOne(['id' => Yii::$app->config->get('site.zoloto')])->populateTree();

        return $this->render('index', [
            'pagesTreeProvider' => $pagesTreeProvider,
            'tvTreeProvider' => $tvTreeProvider,
            'zolotoTreeProvider' => $zolotoTreeProvider,
        ]);
    }

    public function actionIndexList()
    {
        $searchModel = new PageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Page model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Page model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Page();
        $pages = Page::find()->select(['title', 'id'])->indexBy('id')->column();

        $model->is_draft = Page::PUBLISHED;
        $model->is_hidden = Page::VISIBLE;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if($model->id_parent_page)
            {
                $parent = $model::findOne($model->id_parent_page);
                $model->appendTo($parent)->save();
            }
            else
            {
                $model->makeRoot()->save();   
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
            'pages' => $pages,
        ]);
    }

    /**
     * Updates an existing Page model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $pages = Page::find()->select(['title', 'id'])->indexBy('id')->column();
        
        if($model->isRoot() == false)
        {
            $model->id_parent_page = $model->parent['id'];
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate()) 
        {
            
            if($model->isRoot() == false && $model->id_parent_page != $model->parent['id'])
            {
                //изменен родитель
                if($model->isRoot() == false)
                {
                    $parent = $model::findOne($model->id_parent_page);
                    $model->appendTo($parent)->save();
                }
                else 
                {
                    Yii::$app->session->setFlash('error', 'Нельзя переместить корневой элемент');
                }
            }
            else 
            {
                //родитель не изменен
                $model->save();
            }
      
            return $this->redirect(['index']);
        }

        return $this->render('update', [
            'model' => $model,
            'pages' => $pages,
        ]);
    }

    /**
     * Deletes an existing Page model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        // Запрещаем удаление узла, если у него есть потомки
        if (count($model->children) > 0) {
            Yii::$app->session->setFlash('error', 'Элемент не может быть удалён, так как содержит дочерние элементы. Сначала нужно удалить все дочерние элементы');
            return $this->redirect(['index']);
        }
        // Запрещаем удаление корневого элемента
        if ($model->isRoot()) {
            Yii::$app->session->setFlash('error', 'Нельзя удалять корневой элемент');
            return $this->redirect(['index']);
        }
        // Удаляем элемент
        if ($model->delete()) {
            $model->reorder(false);
            Yii::$app->session->setFlash('success', 'Удаление произведено успешно');
        }
        return $this->redirect(['index']);
        //$this->findModel($id)->delete();

        //return $this->redirect(['index']);
    }


    public function actionMoveUp($id)
    {
        $model = $this->findModel($id);
        if ($prev = $model->getPrev()->one()) {
            $model->moveBefore($prev)->save();
            $model->reorder(false);
        } else {
            Yii::$app->session->setFlash('error', 'Невозможно передвинуть элемент вверх. Элемент достиг вершины списка.');
        }
        return $this->redirect(Yii::$app->request->referrer);
    }


    public function actionMoveDown($id)
    {
        $model = $this->findModel($id);
        if ($next = $model->getNext()->one()) {
            $model->moveAfter($next)->save();
            $model->reorder(false);
        } else {
            Yii::$app->session->setFlash('error', 'Невозможно передвинуть элемент вниз. Элемент достиг конца списка.');
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * Finds the Page model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Page the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Page::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
